/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.logadaptor.impl;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Layout;
import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.spi.LoggingEvent;

import com.cqcis.uip.base.logadaptor.AppenderAdapterable;

/**
 * @author huangmy
 * @date 2009-1-8
 */
public class RollingFileAppenderAdapter extends RollingFileAppender implements AppenderAdapterable {
	private Object lock = new Object();
	private File file = null;

	public RollingFileAppenderAdapter() {
		super();
	}

	public RollingFileAppenderAdapter(Layout layout, String filename,
			boolean append) throws IOException {
		super(layout, filename, append);
	}

	public RollingFileAppenderAdapter(Layout layout, String filename)
			throws IOException {
		super(layout, filename);
	}
	
	/**
	 * 最大文件长度
	 * 
	 * @param maxFileSize
	 */
	public void setMaxFileSize(int maxFileSize) {
		super.maxFileSize = maxFileSize;
	}

	@Override
	public void append(LoggingEvent event) {
		synchronized (this) {
			if (file == null) {
				file = new File(getFile());
			}

			if (!file.exists()) { // 不存在, 可能被删除了
				file.getParentFile().mkdirs();// 重建父目录
				activateOptions();
				file = new File(getFile());
			}
		}

		super.append(event);
	}

	/* ------ 修改原方法行为 ------- */

	@Override
	public synchronized void doAppend(LoggingEvent event) {
		synchronized (lock) {
			super.doAppend(event);
		}
	}
}
